/**
 * 
 */
package com.precisosoft.mathematize.server.domain;

import java.sql.Timestamp;
import java.util.Date;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

/**
 * @author jewettdx
 *
 */
public class BaseEntityListener {

	private static final String DEFAULT_USER_NAME = "Administrator";  

	  // Insert auditing fields

	  @PrePersist
	  public void insertAuditingField(Object obj) {
	    if (!(obj instanceof BaseEntity)) {
	      return;
	    }

	    BaseEntity baseEntity = (BaseEntity) obj;
	    Timestamp currentTime = new Timestamp(new Date().getTime());
	    baseEntity.setCreatedTimestamp(currentTime);
	    baseEntity.setUpdatedTimestamp(currentTime);

	    String user = RequestContext.getLocalInstance().getUserName();
	    if (user == null) {
	      user = DEFAULT_USER_NAME; 
	    }
	    
	    baseEntity.setCreatedBy(user);
	    baseEntity.setUpdatedBy(user); 
	  }

	  // Update auditing fields

	  @PreUpdate
	  public void updateAuditingField(Object obj) {
	    if (!(obj instanceof BaseEntity)) {
	      return;
	    }

	    BaseEntity baseEntity = (BaseEntity) obj;
	    Timestamp currentTime = new Timestamp(new Date().getTime());
	    baseEntity.setUpdatedTimestamp(currentTime);

	    String user = RequestContext.getLocalInstance().getUserName();
	    if (user == null) {
	      user = DEFAULT_USER_NAME;
	    }
	    
	    baseEntity.setUpdatedBy(user); 
	  }
}
